package com.my.admin.util;

import ch.qos.logback.core.util.FileSize;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

public class FileUploadUtil {

    public static Rest verify(MultipartFile file, List<String> format, String webServerUrl, FastDFSUtil dfsUtil) {
        if(file.isEmpty()) {
            return Rest.err("上传文件不能为空!");
        }
        String fileName = file.getOriginalFilename();
        if(fileName.lastIndexOf(".") == -1) {
            return Rest.err("请上传正确的图片!");
        }
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!format.contains(suffixName.toUpperCase())) {
            return Rest.err("该图片格式不支持！");
        }
        if(file.getSize() > FileSize.MB_COEFFICIENT * 500) {
            return Rest.err("文件过大，暂不支持！");
        }
        StorePath path = dfsUtil.upload(file);
        if(path == null) {
            Rest.err("文件上传发生错误，请联系管理员！");
        }
        return Rest.ok("文件上传成功!").setData("src", webServerUrl + path.getFullPath());
    }

}
